import {ChangeDetectorRef, Component, OnInit, TemplateRef, ViewChild} from '@angular/core';
import {MyGradesService, WrongTopicModel} from '../../../../core/services/http/exams-manage/my-grades.service';
import {NzTableQueryParams} from 'ng-zorro-antd/table';
import {GoBackParam, PageTypeEnum, SearchCommonVO} from '../../../../core/services/types';
import {finalize} from 'rxjs/operators';
import {MyTableConfig} from '../../../../share/components/ant-table/ant-table.component';
import {ActivatedRoute, Params} from '@angular/router';
import {NzModalService} from 'ng-zorro-antd/modal';
import {NzMessageService} from 'ng-zorro-antd/message';
import {PageHeaderType} from '../../../../share/components/page-header/page-header.component';


interface SearchParam {
  questionContent: string;
}

@Component({
  selector: 'app-exam-wrong-topic',
  templateUrl: './exam-wrong-topic.component.html',
})
export class ExamWrongTopicComponent implements OnInit {
  @ViewChild('operationTpl', {static: true}) operationTpl!: TemplateRef<any>;
  searchParam: Partial<SearchParam> = {};
  currentPage!: number;
  pageTypeEnum = PageTypeEnum;
  tableConfig!: MyTableConfig;
  dataList: WrongTopicModel[] = [];
  checkedCashArray: WrongTopicModel[] = [];
  pageHeaderInfo: Partial<PageHeaderType> = {};

  constructor(private dataService: MyGradesService, private cdr: ChangeDetectorRef, private activatedRoute: ActivatedRoute,
              private modalSrv: NzModalService, private message: NzMessageService) {
    this.currentPage = this.pageTypeEnum.List;
  }

  getDataList(e?: NzTableQueryParams): void {
    this.tableConfig.loading = true;
    this.activatedRoute.params.subscribe((queryParam: Params) => {
      const params: SearchCommonVO<any> = {
        pageSize: this.tableConfig.pageSize!,
        pageNum: e?.pageIndex || this.tableConfig.pageIndex!,
        filters: this.searchParam,
        questionTestId: queryParam['userId'],
        userId: queryParam['questionTestId']
      };
      this.dataService.getWrongTopic(params).pipe(finalize(() => {
        this.tableLoading(false);
      })).subscribe((data => {
        const {list, total, pageNum} = data;
        this.dataList = [...list];
        this.tableConfig.total = total!;
        this.tableConfig.pageIndex = pageNum!;
        this.tableLoading(false);
      }), error => this.tableLoading(false));
    });
  }

  selectedChecked(e: WrongTopicModel[]): void {
    this.checkedCashArray = [...e];
  }


  async returnToList(e?: GoBackParam): Promise<any> {
    this.currentPage = this.pageTypeEnum.List;
    if (!!e && e.refesh) {
      await this.getDataList({pageIndex: e.pageNo} as NzTableQueryParams);
    }
  }

  /*编辑修改*/
  training(): void {
    this.currentPage = this.pageTypeEnum.WrongTopic;
  }

  allDel(): void {
    if (this.checkedCashArray.length > 0) {
      this.modalSrv.confirm({
        nzTitle: '确定要删除吗？',
        nzContent: '删除后不可恢复',
        nzOnOk: () => {
          const tempArrays: number[] = [];
          this.checkedCashArray.forEach((item) => {
            tempArrays.push(item.id);
          });
          this.tableLoading(true);
          this.dataService.delWrongTopic(tempArrays).subscribe(() => {
            if (this.dataList.length === 1) {
              this.tableConfig.pageIndex--;
            }
            this.getDataList();
            this.checkedCashArray = [];
          });
        }
      });
    } else {
      this.message.error('请勾选数据');
      return;
    }
  }

  /*重置*/
  resetForm(): void {
    this.searchParam = {};
    this.getDataList();
  }

  changePageSize(e: number): void {
    this.tableConfig.pageSize = e;
  }

  // 触发表格变更检测
  tableChangeDectction(): void {
    // 改变引用触发变更检测。
    this.dataList = [...this.dataList];
    this.cdr.detectChanges();
  }

  tableLoading(isLoading: boolean): void {
    this.tableConfig.loading = isLoading;
    this.tableChangeDectction();
  }

  ngOnInit(): void {
    this.initTable();
    this.pageHeaderInfo = {
      desc: this.operationTpl,
      breadcrumb: ['在线考试', '错题展示']
    };
  }

  private initTable(): void {
    this.tableConfig = {
      showCheckbox: true,
      headers: [
        {
          title: '题目内容',
          field: 'content',
          width: 350,
        },
        {
          title: '错误次数',
          width: 50,
          field: 'questionCount',
        },
        {
          title: '更新时间',
          width: 100,
          field: 'createTime',
          pipe: 'date:yyyy-MM-dd HH:mm'
        }
      ],
      total: 0,
      loading: true,
      pageSize: 10,
      pageIndex: 1,
    };
  }
}
